package binarySortTree;

public class Node {
    private  int val;
    private Node left;
    private Node right;

    public Node(int val) {
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    @Override
    public String toString() {
        return "Node{" +
                "val=" + val +
                '}';
    }
    /*
    中序遍历
     */
    public void infixOrder(Node root){
        if(root.getLeft()!=null){
            infixOrder(root.getLeft());
        }
        System.out.println(root);
        if(root.getRight()!=null){
            infixOrder(root.getRight());
        }
    }
    /*
    添加节点
     */
    public void addNode(Node node){
        if(node == null){
            return ;
        }
        if(this.getVal() > node.getVal()){
            if(this.getLeft()==null){
                this.setLeft(node);
            }else{
                this.getLeft().addNode(node);
            }
        }else{
            if(this.getRight()==null){
                this.setRight(node);
            }else{
                this.getRight().addNode(node);
            }
        }
    }
    /*
    获取删除的节点
     */
    public Node delNode(int val){
        if(this.val==val){
            return this;
        }else if(this.val>val && this.getRight()!=null){
            this.getRight().delNode(val);
        }else if(this.val<val && this.getLeft()!=null){
            this.getLeft().delNode(val);
        }
        return null;
    }
    /*
    获取删除节点的父节点
     */
    public Node delParentNode(int val){
        if((this.getLeft().val==val&&this.getLeft()!=null)||(this.getRight().val==val&&this.getRight()!=null)){
            return this;
        }else{
            if(val>this.val&&this.getRight()!=null){
                this.getRight().delParentNode(val);
            }else if(val<this.val&&this.getLeft()!=null){
                this.getLeft().delParentNode(val);
            }
        }
        return null;
    }
}
